#!/usr/bin python3
# -*- coding:UTF-8 -*-
# Author: nigo
import plotly.graph_objects as go
import pandas as pd

def get_label(df,value):
    groupby_name = list(df.columns[:2])
    df = df.groupby(groupby_name,as_index=False).sum()
    labels = list(df.iloc[:,1])
    parents = list(df.iloc[:,0])
    values = list(df.iloc[:,-1])
    return labels,parents,values

def df2sunburst(df,top="",value=False):
    if df.empty:
        return [],[],[],[]
    df = df.fillna("")
    labels = []
    parents = []
    values = []
    num = 0
    if top:
        df.insert(0,'top',top)
    else:
        df.insert(0,'top','')
    if value:
        df.columns = list(df.columns[:-1]) + ['value'] # 设置最后一列列名为'value'
    else:
        df['value'] = 0
    num = len(df.columns) -2
    for i in range(num):
        sub_df = df.iloc[:,[i,i+1,-1]]
        tmp_labels,tmp_parents,tmp_values = get_label(sub_df,value)
        labels += tmp_labels
        parents += tmp_parents
        values += tmp_values
    return labels,parents,values

df = pd.read_clipboard(delimiter='\s+',thousands=',')
labels,parents,values= df2sunburst(df,top='',value=True)
print(labels)
print(parents)
print(values)


# sunburst = go.Sunburst(labels=df['小类'],parents=df['大类'],values=df['金额'],branchvalues='total')
sunburst = go.Sunburst(labels=labels,parents=parents)
fig = go.Figure(sunburst)
fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))
# fig.show()

